package com.sjsu.cmpe239.googleservice;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ImageGenerater 
{

	private String imageURL="";
	
	public String getURLForMovie(String movieName)
	{
		URL url;
		
		movieName = movieName + "+movie";
		movieName = movieName.replace(" ", "+");
		System.out.println(movieName);
		try 
		{
			url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" + "v=1.0&q="+movieName+"&start=0&rsz=1");
			URLConnection connection = url.openConnection();
		
			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			while((line = reader.readLine()) != null) {
			builder.append(line);
			}
			
			JSONObject rootObject = new JSONObject(builder.toString());
			JSONArray arrayOfResults =(JSONArray) ((JSONObject) rootObject.get("responseData")).get("results");
			
			JSONObject obj= (JSONObject)arrayOfResults.get(0);
			imageURL = (String) obj.get("url");
			
			
			System.out.println(obj.toString());
			
			System.out.println("\n image URL is: "+ imageURL);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return imageURL;
	}
	
	
	public static void main(String[] args) throws Exception 
	{
		ImageGenerater obj = new ImageGenerater();
		obj.getURLForMovie("Toy Story");
	}
}
